const User = require('../models/user.model.js')
const Role = require('../models/role.model.js')
const Navigation = require('../models/navigation.model.js')
const util = require('../util/util.js')
const JWT = require('../util/jwt.js')
const responseResultData = util.responseResultData
// 创建新的用户对象
exports.login = (req, res) => {
  // 验证请求
  if (!req.body) {
    responseResultData(res, 200, false,  '参数不能为空', '')
    return
  }
  if (!req.body.userName) {
    responseResultData(res, 200, false,  '用户名不能为空', '')
    return
  }
  if (!req.body.passWord) {
    responseResultData(res, 200, false,  '密码不能为空', '')
    return
  }
  // 查询用户是否存在
  User.getByName(req.body.userName, (err, data) => {
    if (err) {
      responseResultData(res, 200, false,  err.message || '查找用户错误', '')
      return
    }
    if(!data) {
      responseResultData(res, 200, false, '未找到该用户')
      return
    }
    const isSuccess = util.compareSync(req.body.passWord, data.passWord)
    if(!isSuccess) {
      responseResultData(res, 200, false, '密码错误')
      return
    }
    // 查询用户权限
    // 获取用户关联的角色
    let navigationIds = []
    Role.getRoleIds(data.id, (err1, roleIdData) => {
      if (err1) {
        responseResultData(res, 200, false,  err1.message || '查找用户角色', '')
        return
      }
      if(roleIdData.length > 0) {
        const roleIds = roleIdData.map(item => item.appRoleId)
        Navigation.getNavigationIds(roleIds,  (err2, navigationIdData) => {
          if (err2) {
            responseResultData(res, 200, false,  err2.message || '查找角色权限', '')
            return
          }
          navigationIds = navigationIdData.map(item => item.navigationId)
          let useInfo = {
            userName: data.userName,
            id: data.id,
            permission: navigationIds.join(',')
          }
          var tokenStr = JWT.setToken(useInfo)
          responseResultData(res, 200, true, '', '', tokenStr)
        })
      }
    })
  })
  
}


